'use strict';

const express = require('express');
const path = require('path');
const favicon = require('serve-favicon');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const session = require('express-session');
const jade = require('jade');
const routesConfig = require('./config.json').routesConfig;
const redisConfig = require('./config.json').redisConfig;
const constant = require('./common/constant');
const logutility = require('./common/logutility');
const RedisStore = require('connect-redis')(session);
const app = express();

// 配置日志
logutility.configure();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
    store: new RedisStore(redisConfig),
    secret: '860DDAE934',
    resave: false,
    saveUninitialized: true
}));

let authmap = new Map();
for (let route of routesConfig) {
    route.routerInstance = require(route.router);
    authmap.set(route.path, route.auth);
}

//默认转至登陆画面
app.get('/', function(req, res) {
    res.redirect('/login');
});

//权限判定
app.all('*', function(req, res, next) {
    let auth = authmap.get(req.path.toString());

    switch (auth) {
        case constant.PUB_STR:
            //公共权限（取件使用）
            next();
            break;
        case constant.COM_STR:
            //快递员和管理员共有权限（登陆、登出、错误画面）
            if (req.session.userTel) {
                next();
            } else {
                res.redirect('/');
            }
            break;
        case constant.ADM_STR:
            //管理员权限
            if (req.session.loginType === constant.LOGIN_TYPE_ADM) {
                next();
            } else {
                res.redirect('/');
            }
            break;
        case constant.COU_STR:
            //快递员权限
            if (req.session.loginType === constant.LOGIN_TYPE_COU) {
                next();
            } else {
                res.redirect('/');
            }
            break;
        default:
            res.redirect('/');
    }
});

//加载各个画面的Router
for (let route of routesConfig) {
    app.use(route.path, route.routerInstance);
}

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    let err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// 异常捕获
app.use(function(err, req, res, next) {
    res.redirect('/error');
});

module.exports = app;